{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python stuff not done in MPR" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List comprehensions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is a common pattern - accumulating into a list:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[4, 1, 9, 4]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "inputs = [2, 1, 3, 2, 4, 5, 6]\n", "result = [] # Start with an empty list\n", "for i in inputs: # Iterate over an input list\n", " if i < 4: # if some condition holds\n", " result.append(i**2) # Append the result of a calculation\n", "result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It's common enough that Python includes dedicated syntax for this:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[4, 1, 9, 4]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result = [i**2 for i in inputs if i < 4]\n", "result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries\n", "\n", "You should be familiar with lists, which are ordered container types." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "lst = [1, 2, 3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can retrieve elements from the list by _indexing_ it" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A dictionary gives us a container like a list, but the indexes can be much more general, not just numbers but strings or sympy variables (and a whole host of other types)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "100" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dic = {'a': 100, 2: 45, 100: 45}\n", "dic['a']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we solve an equation in sympy, the result is a dictionary" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "import sympy\n", "sympy.init_printing()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "x, y = sympy.symbols('x, y')" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "solution = sympy.solve([x - y, 2 + 2*x + y], [x, y])" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAN0AAAAXCAYAAACPt0rIAAAABHNCSVQICAgIfAhkiAAABUZJREFUeJztm2uMXVMUgL/pS9GgXq1nSxoGjUEUP5SptDHRDKr80D8lKAmpaolGIjPxaoc2HuNRaTK9P9ofVCipjKBJqzM0WhlUMyTIxHMmlFZRTBk/1jq5956e1z6POXfu7C85ublnr7X22mfdsx9r7wsWi6WimAdsA/YC/wLn5euOxVLRNAP9QC+wATjD1MDZwH/APqANeBiYmJ5/FcUxwK3Aa8CXwH6ko+kAbgFGhOhPQDqlZ0rutQCbgG/V3i9AF9Ck9VnSJe0YxolfPbAceAsYAD40bcSdqrjQVHEIcgfS1h+AdcAypKPZo/dfAWoC9Beo3IySe/8gs4Q2JBCtwHaV+x44JdUWWNKOYdL4fYQMWuNMGvGgVjDLRGmIcgXQyMG94UTgG+Q5zA3Qbwd+BkaW3BvrI/uo2ns+lqcWP9KOYdL4rVM5o861WZXqA2TeVpnrXPdrgIKWLTeptAJ5AGlHq0/5kcDfwJqI9urU3jvJXUvMEsSXJT7lZyJte2/QPMqGNGMYNX4FlZvsLgib54ZxHzKEPkJ5L78CmA+sBpZGcOymhH5kSb9+HvApnw2MAV6NaK9RPz9N4lRKdOjnJT7lrUhc7wqwUWB4xTDT+D2FPMyLQ+QKlD90p1d5ifCX2q1baYwCdiI+Xukjsx74Hf/pyL3IrOFJYKva+gQ4Lk1HYzIa+BOZfrm5AfH16RAbBao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OpxWKxWCwWi8VSyv/ZG+rF45b2DwAAAABJRU5ErkJggg==", "text/latex": [ "$$\\left \\{ x : - \\frac{2}{3}, \\quad y : - \\frac{2}{3}\\right \\}$$" ], "text/plain": [ "{x: -2/3, y: -2/3}" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "solution" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(solution)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This means we can find the value of one of the answers by indexing." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAADIAAAAUCAYAAADPym6aAAAABHNCSVQICAgIfAhkiAAAAghJREFUSInt1k2IjVEcx/GPmUmzk3cbC1YWU0pZSmMWFho12dlY0KSUJimlZDbeosSNJRIrYqVZSMlLqZHBlImoyWQyhYjyNmJx/je3O/Pc55k718tivvX01P/8/i/nPM/5n8MME5iPbbiK5/iMD7iDrWjK8V+MHzhZYTuCGxiJeO8wgP2R74+wHT8xios4hDN4H/bLmFXDvzt07RW2b7gXcQ6jhP7QvcLShs4gWIdOE1d+CV5G8k01/PvwBs0VttYM7YGId7quSqfB3khcyhifg684WzDeyoh3vWzI+28bxfd4j2eMb8BsXCkYrzPej6dT1FRpwaC0guszNJfwSfavtBu9OI7bEesRFjay0DyOReJrGeOt+ChNJovXEaP89EldLpPhKoe850LOJHaGbgjzMjQbQ7M5J5YovgtPpe64qjzQUiV8gS8FApYZrTG2AyfwBB3SGTAZXVKbzfpilYxJ59QDPMN5tBUtth56pFUexKIaumap5fbVkWMgciyow7cQeyLBQIEk7aHtriPPWPjOrcM3l30R/L7sPVFJSbqWTLZxV0iHaTVNfh+Id8vGWleGqbIF56KwknTPqmY4NGVGwrZmEm0PjuKWtHffShNei+VSJ+uQ9mBD6ZXf5W5W6FeHbVdGvDacwkNpH41Li9MfuYp88b/CQWkiy/51IdNlSFrtGWb4n/kFujaNnxDpNYQAAAAASUVORK5CYII=", "text/latex": [ "$$- \\frac{2}{3}$$" ], "text/plain": [ "-2/3" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "solution[x]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You are familiar with lists:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "x = 1, 2, 3 \n", "\n", "a, b, c = x\n", " \n", "\n", "a, b, c = 1, 2, 3\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "def f(x):\n", " Ca, Cb, Cc = x" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "l = [1, 2, 3, 4]" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(l)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tuples are like lists, but they are created with commas:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "t = 1, 2, 3, 4" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(t)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In some cases it is useful to use parentheses to group tuples (but note that they are not required syntax:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "t2 = (1, 2, 3, 4)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(t2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is important to understand that the comma, not the parentheses make tuples:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "only_one = (((((((1)))))))" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(only_one)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "only_one = 1," ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(only_one)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAA0AAAASCAYAAACAa1QyAAAABHNCSVQICAgIfAhkiAAAAHZJREFUKJFjYKACCGFgYJjMwMBwmIGB4RMDA8N/BgaGJYQ0XYAq/MzAwHCdWE2ODAwMqgwMDIwMDAwOuDSxoPH3EzKVgYGBgYkYRaOaBlwTeuQGQDEDAwODBJS2ZGBgWABlv2FgYChBN6SBAZJ0cOEH5LiMzgAA6XoX52TB9a4AAAAASUVORK5CYII=", "text/latex": [ "$$1$$" ], "text/plain": [ "1" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(only_one)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The only exception to this rule is that an empty tuple is built with `()`:\n", "\n" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "empty = ()" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(empty)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAABHNCSVQICAgIfAhkiAAAAM5JREFUOI3N0rEyQ0EUxvEfJcMVWhoZ8Qpq75PnoDJ0Kl5BK0U67yAUiUYmpZGYoRDNuePOkXszYxS+5ps95/x3Z3c//lC7uMIz3jHCOVpNUBsTzHGDU/RjfY+dOvA2hrqpfhb1y0XQfjSHWE29DUwxw7o0cBzew2cCX3GHNRxl8DD8oeYaj+GdDBbhLzVgWd/K4DKthM8zWO5YWKzN6lwVHIR3asCD8B9v0Lb8O97Ed2T9KgDlqdXInfiO3EBD5GAP1xjjA0+4wHYT9I/1BRgnMa7SDNsAAAAAAElFTkSuQmCC", "text/latex": [ "$$0$$" ], "text/plain": [ "0" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(empty)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The differences between tuples and lists are that tuples are immutable (they cannot be changed in place)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "l.append(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we were to run \n", "\n", "```\n", "t.append(1)\n", "```\n", "\n", "We would see\n", "```\n", "---------------------------------------------------------------------------\n", "AttributeError Traceback (most recent call last)\n", " in ()\n", "----> 1 t.append(1)\n", "\n", "AttributeError: 'tuple' object has no attribute 'append'\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tuple expansion\n", "\n", "A very useful and general feature of the assignment operator in Python is that tuples will be expanded and assigned in matched patterns:" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "a, b = 1, 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is quite sophisticated and can handle nested structures and expanded to lists:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "[(a, b,), c, d] = [(1, 2), 3, 4]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The for loop in Python\n", "\n", "[This talk](https://nedbatchelder.com/text/iter.html) is excellent for understanding the way that Python \"wants\" to use the for loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### zip" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's say we're trying to calculate the credit-weighted average of a student's marks using loops:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "credits = [8, 16, 8, 8, 16]\n", "marks = [75, 60, 60, 75, 45]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One way is to use indexing:" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "60.0\n" ] } ], "source": [ "weightedsum = 0\n", "creditsum = 0\n", "for i in range(len(credits)):\n", " weightedsum += credits[i]*marks[i]\n", " creditsum += credits[i]\n", "\n", "avg = weightedsum/creditsum\n", "print(avg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But Python supplies a method which allows us to iterate directly over the pairs:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "60.0\n" ] } ], "source": [ "weightedsum = 0\n", "creditsum = 0\n", "for credit, mark in zip(credits, marks):\n", " weightedsum += credit*mark\n", " creditsum += credit\n", "\n", "avg = weightedsum/creditsum\n", "print(avg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This `zip` function returns an iterator which groups its inputs into tuples, suitable for expansion in the for loop. We can see the effect if we convert to a list:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAkIAAAAVCAYAAACqs4FmAAAABHNCSVQICAgIfAhkiAAACTZJREFUeJztnX+MHkUZxz/UQnuF0ooVSRQBocVKEyKSCpKWpUgF5ZfxR6IBrdHEGMWiJEQNpi+gVJEQiQQIRDjQxPArFKyihz9eCygQo6h/2EI4XkOFWkV+c1Lann88s7nt3szuO/Pu3u5zN5/kzab7zM4+s9+Zp7OzM3MQiUQikUgkEiEBxjO/zY50twDbgX2nxi2Vv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lTEN2fR3rnWYZppuy+voZuqKhJd21tN6S+heioSUMI03GY9sdfCI/B2jTMk1BPDB6mWd2zdHDPEapD95QuAZOlAT5h7F+02GYhu1qOIxt33czE9+rd5vxay3W3GNs5BQ7Xyf2UT9LrIMN59wLXIOW6Awkq48DPkJ64jZ8gvXXbktCmyl6k49lIIxlmYsXBE5lzV1iuOZCJSrnJpLkdKffryK6neZoqu6+vhwP/Muk3ICs0fmP+vQX3ELcm3bW13ZD6FqKjJg0hTEcN8RfCY7A2DWFqYnDTumfp4O4Idahe95QugR2hfZC3jYcd9r2RfSweQhriTuQb3UZkWNrGn01a1x+wrJOlSHmfongr7hORB7sZ6Vm/jgxv3of87Z69HNctQARzbWLWVNmLdOyw5/fb/K/nyPMA5O36SWRo9llkh9vjHOmb1N3X14OBm5Bh7R3I1u1XYX9TAZ26a2u7vhqCn44aNQR/HTXEXwiLwVo17FB/DG5S9zwd3B2hOnRP6RLYEQLZa2OcaibcLUQmx7V1SeegnIc8qxUWW9Nlr1JHX5oue93MBN2bLkfdRA31MxM0DKHpstdNke5ZupR0hNLfZkuaucibVNk33X44Axn2OqiCvNrGEPA0Moxno+myV6mjL02XvU5miu5Nl6NOoob6mSkahtB02eukTPdFTB5hm8ShyGhQ+nNNNFqJLHlzLRmPyLBvB3mmbSXqWD1Rd/1EDfUTNZyZlOk+jz37OJ3aPYpEIpFIJBKJRCKRSCQSibSU/wPkTylAbOn78AAAAABJRU5ErkJggg==", "text/latex": [ "$$\\left [ \\left ( 8, \\quad 75\\right ), \\quad \\left ( 16, \\quad 60\\right ), \\quad \\left ( 8, \\quad 60\\right ), \\quad \\left ( 8, \\quad 75\\right ), \\quad \\left ( 16, \\quad 45\\right )\\right ]$$" ], "text/plain": [ "[(8, 75), (16, 60), (8, 60), (8, 75), (16, 45)]" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(zip(credits, marks))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These pairs are then assigned out to the arguments in the for loop above" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## lambda" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some functions expect functions as arguments. For instance, `scipy.optimize.fsolve` solves equations numerically:" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "def f(x):\n", " return x**2 - 3" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "import scipy" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "import scipy.optimize" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([1.73205081])" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "scipy.optimize.fsolve(f, 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For very simple functions, `lambda` allows us to construct functions in a more compact way and not give them a name:" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([1.73205081])" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "scipy.optimize.fsolve(lambda x: x**2 - 3, 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function constructed by lambda works the same as the one constructed by def in most ways. My recommendation is to use lambda with caution. It is never *necessary* to use `lambda`. I include this section mostly so that you can understand what this does if you encounter it in documentation." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.6" } }, "nbformat": 4, "nbformat_minor": 2 }